package com.zhugang.week07;

/**
 * @program algorithms
 * @description: maxPathSum
 * @author: chanzhugang
 * @create: 2022/07/28 17:36
 */
public class MaxPathSum {

    /**
     * 124 二叉树中的最大路径和
     *
     * @param root
     * @return
     */
    private int result = -1001;

    public int maxPathSum(TreeNode root) {
        // 路径和是路径中各节点值的总和
        // 没理解
        dfs(root);
        return result;
    }

    private int dfs(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftMaxPath = dfs(root.left);
        int rightMaxPath = dfs(root.right);

        int max = root.val;
        if (leftMaxPath > 0) max += leftMaxPath;
        if (rightMaxPath > 0) max += rightMaxPath;
        if (max > result) {
            result = max;
        }

        int ret = root.val;
        if (ret < leftMaxPath + root.val) ret = leftMaxPath + root.val;
        if (ret < rightMaxPath + root.val) ret = rightMaxPath + root.val;
        return ret;
    }


    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}